package com.example.taobaounion3.presenter.impl;

import com.example.taobaounion3.model.Api;
import com.example.taobaounion3.model.domain.Histories;
import com.example.taobaounion3.model.domain.SearchRecommend;
import com.example.taobaounion3.model.domain.SearchResult;
import com.example.taobaounion3.presenter.ISearchPresenter;
import com.example.taobaounion3.utils.JsonCacheUtil;
import com.example.taobaounion3.utils.LogUtils;
import com.example.taobaounion3.utils.RetrofitManager;
import com.example.taobaounion3.view.ISearchViewCallback;
import com.lcodecore.tkrefreshlayout.utils.LogUtil;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class SearchPresenterlmpl implements ISearchPresenter {
    private Api mApi;
    private ISearchViewCallback mSearchPageCallback = null;
    private static final int DEDAULT_PAGE = 0;
    private static JsonCacheUtil mJsonCacheUtil;
    /**
     * 搜索的当前页面
     */
    private int mCurrentPage = DEDAULT_PAGE;
    private String mCurrentKeyword=null;

    public SearchPresenterlmpl() {
        RetrofitManager retrofitManager = RetrofitManager.getOurInstance();
        Retrofit retrofit = retrofitManager.getRetrofit();
        mApi = retrofit.create(Api.class);
         mJsonCacheUtil = JsonCacheUtil.getInstance();

    }

    @Override
    public void getHistories() {
        Histories histories = mJsonCacheUtil.getValue(KEY_HISTORIES, Histories.class);
        if (mSearchPageCallback!=null&&
                histories!=null&&
                histories.getHistories()!=null&&
                histories.getHistories().size()!=0) {
            mSearchPageCallback.onHistoriesLoaded(histories.getHistories());
        }
    }

    @Override
    public void delHistories() {
        mJsonCacheUtil.delCache(KEY_HISTORIES);
    }

    private static final String KEY_HISTORIES="key_histories";
    private static final int DEFAULT_HISTORIES_SIZE=10;
    private  int mHistoriesMaxSize =DEFAULT_HISTORIES_SIZE;
    /**
     * t添加历史记录
     * @param history
     */
    private void saveHistory(String history){
        Histories histories = mJsonCacheUtil.getValue(KEY_HISTORIES, Histories.class);
        //如果已经存在，就删除，然后再添加
        List<String> historiesList =null;
        if (histories!=null&&histories.getHistories()!=null) {
            historiesList=histories.getHistories();
            if (historiesList.contains(history)) {
                historiesList.remove(history);
            }
        }
        //去重完成
        //处理没有数据的情况
        if (historiesList==null) {
            historiesList=new ArrayList<>();
        }
        if (histories==null) {
            histories=new Histories();
        }
        histories.setHistories(historiesList);
        //对个数进行限制
        if (historiesList.size()>mHistoriesMaxSize) {
            historiesList=historiesList.subList(0,mHistoriesMaxSize);
        }
        //添加记录
        historiesList.add(history);
        //保存记录
        mJsonCacheUtil.saveCache(KEY_HISTORIES,historiesList);
    }

    @Override
    public void doSearch(String keyword) {
        if (mCurrentKeyword!=null||!mCurrentKeyword.endsWith(keyword)) {
            this.saveHistory(keyword);
            this.mCurrentKeyword=keyword;
        }

        //更新UI状态
        if (mSearchPageCallback != null) {
            mSearchPageCallback.onLoading();
        }
        Call<SearchResult> task = mApi.doSearch(mCurrentPage, keyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                LogUtils.d(SearchPresenterlmpl.this, "doSearch code-->" + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    handleSearchResult(response.body());
                } else {
                    onError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                t.printStackTrace();
                onError();
            }
        });
    }

    private void onError() {
        if (mSearchPageCallback != null) {
            mSearchPageCallback.onError();
        }
    }

    private boolean isResultEmpty(SearchResult result) {
        try {
            return result == null || result.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data().size() == 0;
        } catch (Exception e) {
            return false;
        }
    }


    private void handleSearchResult(SearchResult result) {
        if (mSearchPageCallback!=null) {
            if (isResultEmpty(result)) {
                //数据为空
                mSearchPageCallback.onEmpty();
            } else {
                mSearchPageCallback.onSearchSuccess(result);
            }
        }
    }

    @Override
    public void research() {
        if (mCurrentKeyword==null){
            if (mSearchPageCallback != null) {
                mSearchPageCallback.onEmpty();
            }
        }else {
            //可以重新搜索
            this.doSearch(mCurrentKeyword);
        }
    }

    @Override
    public void loaderMore() {
        mCurrentPage++;
        //进行搜索
        if (mCurrentKeyword==null){
            if (mSearchPageCallback != null) {
                mSearchPageCallback.onEmpty();
            }
        }else {
            //可以重新搜索
            this.doSearchMore();
        }
    }

    private void doSearchMore() {
        Call<SearchResult> task = mApi.doSearch(mCurrentPage, mCurrentKeyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                LogUtils.d(SearchPresenterlmpl.this, "doSearchMore code-->" + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    handleMoreSearchResult(response.body());
                } else {
                    onLoaderMoreError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                t.printStackTrace();
                onLoaderMoreError();
            }
        });
    }

    /**
     * 处理加载更多结果
     * @param result
     */
    private void handleMoreSearchResult(SearchResult result) {
        if (mSearchPageCallback!=null) {
            if (isResultEmpty(result)) {
                //数据为空
                mSearchPageCallback.onMoreLoadedEmpty();
            } else {
                mSearchPageCallback.onMoreLoaded(result);
            }
        }
    }

    /**
     * 加载更多失败
     */
    private void onLoaderMoreError() {
        mCurrentPage--;
        if (mSearchPageCallback != null) {
            mSearchPageCallback.onMoreLoadedError();
        }
    }

    @Override
    public void getRecommentWords() {
        Call<SearchRecommend> task = mApi.getRecommendWords();
        task.enqueue(new Callback<SearchRecommend>() {
            @Override
            public void onResponse(Call<SearchRecommend> call, Response<SearchRecommend> response) {
                int code = response.code();
                LogUtils.d(SearchPresenterlmpl.this, "recommend code-->" + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    //处理结果
                    if (mSearchPageCallback != null) {
                        mSearchPageCallback.onRecommendWordsLoaded(response.body().getData());
                    }
                } else {

                }
            }

            @Override
            public void onFailure(Call<SearchRecommend> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    @Override
    public void registerViewCallback(ISearchViewCallback callback) {
        this.mSearchPageCallback = callback;
    }

    @Override
    public void unregisterViewCallback(ISearchViewCallback callback) {
        this.mSearchPageCallback = null;
    }
}
